package com.hospitalmanagementsystem.controller;

import com.hospitalmanagementsystem.dto.AuthResponseDTO;
import com.hospitalmanagementsystem.dto.LoginRequestDTO;
import com.hospitalmanagementsystem.dto.RegisterRequestDTO;
import com.hospitalmanagementsystem.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthService authService;

    @Autowired
    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody RegisterRequestDTO registerRequestDTO) {
        try {
            String response = authService.registerUser(registerRequestDTO);
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody LoginRequestDTO loginRequestDTO) {
        try {
            AuthResponseDTO authResponseDTO = authService.loginUser(loginRequestDTO);
            return ResponseEntity.ok(authResponseDTO);
        } catch (Exception e) {
            // Catching generic Exception for authentication failures (e.g., BadCredentialsException)
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Login failed: " + e.getMessage());
        }
    }
} 